<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <el-button type="primary" plain style="margin-top: 1%;" @click="GoBack">返回</el-button>
            </el-header>
            <el-main>
                <div>
                    <el-container>
                        <el-aside width="25%">
                            <div style="float: right;margin-right: 10%;">

                                <div style="display: inline-block;">
                                    <el-form label-width="100px" style="margin-top: 20px;">
                                        <h2>门店地址</h2>&nbsp;
                                        <el-form-item label="省份" style="display: inline-block;">
                                            <el-select v-model="locationInfo.selectedProvince"
                                                @change="handleProvinceChange">
                                                <el-option v-for="province in locationInfo.provinceList"
                                                    :key="province.pid" :label="province.pname"
                                                    :value="province.pid"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="城市" style="display: inline-block;">
                                            <el-select v-model="locationInfo.selectedCity" @change="handleCityChange">
                                                <el-option v-for="city in locationInfo.cityList" :key="city.cid"
                                                    :label="city.cname" :value="city.cid"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="区域" style="display: inline-block;">
                                            <el-select v-model="locationInfo.selectedAreaId">
                                                <el-option v-for="area in locationInfo.areaList" :key="area.lid"
                                                    :label="area.lname" :value="area.lid"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <br>
                                        <el-form-item label="预约取车时间" style="display: inline-block;">
                                            <el-date-picker v-model="locationInfo.reserveTime" type="date"
                                                placeholder="选择日期" :disabled-date="disabledDate"
                                                value-format="YYYY-MM-DD" />
                                        </el-form-item>
                                    </el-form>

                                </div>
                            </div>
                        </el-aside>
                        <el-main>
                            <div>
                                <img :src="carDetail.imgpath" :alt="carDetail.carname" style="width: 100%;" />

                            </div>
                        </el-main>
                        <el-aside width="33%">
                            <div style="margin-left: 10%;">
                                <h3>汽车名称：{{ carDetail.carname }}</h3>
                                <el-tag type="primary">{{ carDetail.brandname }}</el-tag>
                                <h1>车牌号：{{ carDetail.plate }}</h1>
                                <h1>汽车类型：{{ carDetail.ctname }}</h1>
                                <h1>车辆级别：{{ carDetail.level }}</h1>
                                <h1>排放量：{{ carDetail.displacement }}</h1>
                                <h1>能源类型：{{ carDetail.ename }}</h1>
                                <h1>挡位：{{ carDetail.gname }}</h1>
                                <div>
                                    <h1 v-if="carDetail.status == 1">状态：待租出</h1>
                                    <h1 v-if="carDetail.status == 2">状态：已租出</h1>
                                    <h1 v-if="carDetail.status == 3">状态：已下线</h1>
                                </div>
                                <h3>租借价格：￥{{ carDetail.price }}起</h3>
                                <h3 style="display: inline;">租借天数：</h3>
                                <div id="days" style="display: inline-block;">
                                    <el-button type="primary" plain @click="DelNum"><el-icon>
                                            <Minus />
                                        </el-icon></el-button>
                                    <el-button type="primary" plain>{{ num }}天</el-button>
                                    <el-button type="primary" plain @click="PlusNum"><el-icon>
                                            <Plus />
                                        </el-icon></el-button>
                                </div>
                                <br />
                            </div>
                            <div style="margin-left: 10%;margin-top: 2%;">
                                <el-button type="primary" plain @click="submitOrder" v-if="carDetail.status == 1">
                                    <el-icon>
                                        <Money />
                                    </el-icon>预约用车
                                </el-button>
                                <el-button type="primary" plain @click="submitOrder" v-if="carDetail.status != 1"
                                    disabled>
                                    <el-icon>
                                        <Money />
                                    </el-icon>预约用车
                                </el-button>
                            </div>
                        </el-aside>
                    </el-container>
                </div>
            </el-main>
        </el-container>
    </div>
</template>
<script setup>
import request from '../utils/request';
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ShoppingCart, Money, Minus, Plus } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/userStore';

let route = useRoute();
let router = useRouter();
const userStore = useUserStore();
const username = userStore.userinfo.username;

const num = ref(1);
const DelNum = () => {
    if (num.value >= 2) {
        num.value--;
    }
};
const PlusNum = () => {
    num.value++;
};
const carDetail = reactive({});

// 修改区域选择相关数据结构，统一使用ID进行绑定
const locationInfo = reactive({
    provinceList: [],
    cityList: [],
    areaList: [],
    selectedProvince: null,
    selectedCity: null,
    //存储区域ID
    selectedAreaId: null,
    reserveTime: null // 预约取车时间
});
//限制不可选当天以前的时间
const disabledDate = (time) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return time.getTime() < today.getTime();
};
onMounted(async () => {
    const carid = route.params.carid;
    let r = await request.get(`car/findByCarid/${carid}`);
    if (r.data.success) {
        Object.assign(carDetail, r.data.data);
    }
    // 获取省份列表
    let provinceRes = await request.get('/province/list');
    if (provinceRes.data.success) {
        locationInfo.provinceList = provinceRes.data.data;
    }
});

// 省份选择变化时获取城市列表
const handleProvinceChange = async (pid) => {
    locationInfo.selectedCity = null;
    // 重置区域ID
    locationInfo.selectedAreaId = null;
    if (pid) {
        let cityRes = await request.get(`/city/listByPid/${pid}`);
        if (cityRes.data.success) {
            locationInfo.cityList = cityRes.data.data;
        }
    } else {
        locationInfo.cityList = [];
    }
};

// 城市选择变化时获取区域列表
const handleCityChange = async (cid) => {
    // 重置区域ID
    locationInfo.selectedAreaId = null;
    if (cid) {
        let areaRes = await request.get(`/area/listByCid/${cid}`);
        if (areaRes.data.success) {
            locationInfo.areaList = areaRes.data.data;
        }
    } else {
        locationInfo.areaList = [];
    }
};

const submitOrder = async () => {
    if (!locationInfo.selectedAreaId) {
        ElMessage.error("请选择取车地点");
        return;
    }
    if (!locationInfo.reserveTime) {
        ElMessage.error("请选择预约取车时间");
        return;
    }
    try {
        let userRes = await request.get(`/user/findIdByName/${username}`);
        if (!userRes.data.success) {
            ElMessage.error("获取用户ID失败，请检查");
            return;
        }
        const userid = userRes.data.data;
        const carid = route.params.carid;
        const days = num.value;
        const totalprice = carDetail.price * days;
        // 将预约取车时间转为 Date 对象
        const createtime = new Date(locationInfo.reserveTime);
        const endtime = new Date(createtime.getTime() + days * 24 * 60 * 60 * 1000);
        const starttime = new Date();
        const orderData = {
            userid,
            carid,
            days,
            totalprice,
            starttime,
            createtime,
            endtime,
            status: 1,
            lid: locationInfo.selectedAreaId
        };

        let orderRes = await request.post('/order/create', orderData);
        if (orderRes.data.success) {
            ElMessage.success("下单成功");
            router.push({ path: '/MainFrameView/orders' });
        } else {
            ElMessage.error("下单失败：" + (orderRes.data.msg || "未知错误"));
        }
    } catch (error) {
        console.error("下单异常：", error);
        ElMessage.error("下单异常，请稍后重试");
    }
};

const GoBack = () => {
    history.back();
};
</script>
<style>
/* 背景图 */
.common-layout {
    position: fixed;
    width: 100%;
    height: 100%;
    background-image: url("../assets/bgc.jpg");
    background-size: cover;
}

.el-form-item__label {
    color: aliceblue;
}

h1,
h2,
h3 {
    color: aliceblue;
}
</style>
